#ifndef __MY_CLOUD__
#define __MY_CLOUD__
#include<string>
#include"data.hpp"
#include"httplib.h"
#include<Windows.h>



namespace cloud
{
#define SERVER_ADDR "192.168.37.54"
#define SERVER_PORT 8080
	class BackUp
	{
	public:
		BackUp(const std::string& back_dir,const std::string& back_file)
			:_back_dir(back_dir)
			,_data(new DataManager(back_file))
		{ }

		std::string GetFileIdentifier(const std::string& filename)
		{
			FileUtil fu(filename);
			std::stringstream ss;
			ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.LastMTime();
			return ss.str();
		}

		bool RunModul()
		{
			while (1)
			{
				FileUtil fu(_back_dir);
				std::vector<std::string> arr;
				fu.ScanDirectory(&arr);
				for (auto& a : arr)
				{
					//std::cout << a << std::endl;
					if (IsNeedUpload(a))
					{
						if (Upload(a))
						{
							std::string id = GetFileIdentifier(a);
							_data->Insert(a, id);
						}
					}
					
				}

				Sleep(1);
			}
		}

		bool Upload(const std::string& filename)
		{
			FileUtil fu(filename);
			std::string body;
			fu.GetContent(&body);
			httplib::Client client(SERVER_ADDR, SERVER_PORT);
			httplib::MultipartFormData item;
			item.name = "file";
			item.filename = fu.FileName();
			item.content = body;
			item.content_type = "application/octet-stream";
			httplib::MultipartFormDataItems items;
			items.push_back(item);

			auto res=client.Post("/upload", items);
			if (!res || res->status != 200)
			{
				return false;
			}

			std::string str = res->body;
			std::string value = res->get_header_value("Content-Disposition");
			size_t pos = value.find("filename=");
			std::string file = value.substr(pos + 9);
			FileUtil tmp(file);
			tmp.SetContent(str);

			return true;


		}

		bool IsNeedUpload(const std::string& filename)
		{
			std::string id;
			if (_data->GetOneByKey(filename, &id) == true)
			{
				std::string new_id = GetFileIdentifier(filename);
				if (new_id == id)
				{
					return false;
				}
			}
			FileUtil fu(filename);
			if (time(nullptr) - fu.LastMTime() < 5)
			{
				return false;
			}
			return true;
		}
	private:
		std::string _back_dir;
		DataManager* _data;
	};
}

#endif
